import re
import time
import random
import urllib

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.action_chains import ActionChains

from getPosition import get_pos
# ch_options = Options()
# # 配置无头模式
# ch_options.add_argument('--headless')

# 本次模拟登录的方式是账号密码的登录：但是会存在账号异常，扫码登陆
driver = webdriver.Chrome()
try:
    driver.get('https://accounts.douban.com/passport/login?source=movie')
    pass_click = driver.find_element(By.XPATH,'//*[@id="account"]/div[2]/div[2]/div/div[1]/ul[1]/li[2]')
    pass_click.click()
    # 整体等待五秒
    print('正在点击密码按钮')
    time.sleep(5)

    # 浏览器隐式等待
    driver.implicitly_wait(3)
    print('**************正在输入账号')
    userInput = driver.find_element(By.ID,'username')
    userInput.send_keys('19959797519')
    time.sleep(2)
    print('等待两秒')
    print('**************正在输入密码')
    passwordInput = driver.find_element(By.ID,'password')
    passwordInput.send_keys('a34311872')
    time.sleep(2)
    print('**************准备点击按钮')
    loginButton = driver.find_element(By.XPATH,'//*[@id="account"]/div[2]/div[2]/div/div[2]/div[1]/div[4]/a')
    loginButton.click()
    time.sleep(3)
    # 浏览器隐式等待
    driver.implicitly_wait(5)
    # 此时需要切换到弹出的滑块区域，需要切换frame窗口
    driver.switch_to.frame('tcaptcha_iframe_dy')
    # 等待滑块验证码图片加载后，再做后面的操作
    WebDriverWait(driver,10).until(EC.visibility_of_element_located((By.ID,'slideBg')))
    # 获取滑块验证图片下载路径，并下载到本地
    bigImage = driver.find_element(By.ID,'slideBg')
    s = bigImage.get_attribute("style")
    # 获取图片的下载地址
    p = 'background-image: url\(\"(.*?)\"\);'
    bigImageSrc = re.findall(p,s,re.S)[0]
    print(bigImageSrc)
    urllib.request.urlretrieve(bigImageSrc,'bigImage.png')
    dis = get_pos(imageSrc='bigImage.png')
    time.sleep(5)

    # 定位滑块元素
    slide = driver.find_element(By.XPATH,'//*[@id="tcOperation"]/div[6]')

    # 小滑块到目标区域的移动距离（缺口坐标的水平位置距离小滑块的水平坐标相减的差）
    # 新缺口坐标=原缺口坐标*新画布宽度/原画布宽度
    newDis = int(dis*340/672-slide.location['x'])
    driver.implicitly_wait(5)

    # 按下小滑块按钮不动
    ActionChains(driver).click_and_hold(slide).perform()
    # 移动小滑块，模拟人的操作，一次次移动一点点
    i = 0
    moved = 0
    while moved<newDis:
        x = random.randint(3,10)
        moved+=x
        ActionChains(driver).move_by_offset(xoffset=x,yoffset=0).perform()
        print("第{}次移动后，位置为{}".format(i, slide.location['x']))
        i+=1
    # 移动完之后，松开鼠标
    ActionChains(driver).release().perform()
    time.sleep(5)

finally:
    # 关闭浏览器
    driver.quit()